package com.example.recyclerviewstudy.Adapter.firstRecyclerAdapter;

import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.recyclerviewstudy.R;

/**
 * Created by frc on 16-5-26.
 */
public class FirstRecyclerViewAdapter extends RecyclerView.Adapter<FirstRecyclerViewHolder> {
    private SparseArray<String> ItemDates;
    private OnItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.mOnItemClickListener = onItemClickListener;
    }

    public FirstRecyclerViewAdapter(SparseArray<String> itemDates) {
        this.ItemDates = (itemDates != null ? itemDates : new SparseArray<String>());
    }

    @Override
    public FirstRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View ItemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_first_recycler_view, parent, false);
        return new FirstRecyclerViewHolder(ItemView);
    }

    @Override
    public void onBindViewHolder(final FirstRecyclerViewHolder holder, int position) {
        holder.textView.setText(ItemDates.get(position + 'A'));
        if (mOnItemClickListener != null) {
            holder.textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickListener.onItemClick(holder.textView, pos);
                }
            });
            holder.textView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickListener.onItemLongClick(holder.textView, pos);
                    return false;
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return (ItemDates != null) ? ItemDates.size() : 0;
    }

    public void addItem(int position, String string) {
        ItemDates.append(position, string);
        notifyItemInserted(position);
    }

    public void removeItem(int position) {
        ItemDates.remove(position);
        notifyItemRemoved(position);
    }
}
